﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Media;

namespace Zero.UControl.Demo.Views.UAdorner.Component
{
    public class SelectionAdorner : ElementDecoratorBase
    {
        private readonly Pen _borderPen;
        private const double Padding = 4; // 边缘间距（外扩尺寸）

        public SelectionAdorner(UIElement adornedElement) : base(adornedElement)
        {
            var dashStyle = new DashStyle(new double[] { 4, 4 }, 0);
            _borderPen = new Pen(Brushes.DeepSkyBlue, 1)
            {
                DashStyle = dashStyle
            };
            IsHitTestVisible = false;   // 不干扰点击事件
        }

        public override void Attach(UIElement element, Canvas canvas)
        {
            base.Attach(element, canvas);
            AdornerLayer adornerLayer = AdornerLayer.GetAdornerLayer(element);
            if (adornerLayer != null)
            {
                adornerLayer.Add(new SelectionAdorner(element));
            }
        }

        protected override void OnRender(DrawingContext dc)
        {
            if (AdornedElement is FrameworkElement fe)
            {
                double scaledWidth = fe.ActualWidth;
                double scaledHeight = fe.ActualHeight;

                var rect = new Rect(
                    -Padding,
                    -Padding,
                    scaledWidth + Padding * 2,
                    scaledHeight + Padding * 2
                );

                dc.DrawRectangle(null, _borderPen, rect);
            }
        }
    }
}
